<template>
  <div>
    直播
    <div id="dplayer"></div>
    <div>
      <input v-model="msg" />
      <button @click="send">发送</button>
      <button @click="close">关闭</button>
    </div>
  </div>
</template>
<script setup>
import DPlayer from 'dplayer'
import Hls from 'hls.js'
import { ref, onMounted } from 'vue'
let msg = ref() //消息
let ws = ref(new WebSocket('ws://192.168.58.101:8080'))

let send = () => {
  //发送  发送给后端
  // alert(msg.value);
  ws.value.send(
    JSON.stringify({
      type: 1,
      msg: msg.value
    })
  )
}
let close = ()=>{
    ws.value.send(
        JSON.stringify({
            type:2,
            msg:"关闭"
        })
    )
}

onMounted(() => {
  //页面结构加载完成的生命周期
  let container = document.getElementById('dplayer')
  ws.value.onmessage = (evt) => {
    // console.log(evt.data);
    let info = JSON.parse(evt.data)
    if (info.type == 1) {
      let div = document.createElement('div')
      div.innerHTML = info.msg;
      Object.assign(div.style, {
        position: 'absolute',
        color: 'red',
        left: container.offsetWidth + 'px',
        top: Math.round(Math.random() * 100) + 'px'
      }) //后面的覆盖前面的对象的属性
      container.appendChild(div)

      div.timer = setInterval(() => {
        div.style.left = div.offsetLeft - 10 + 'px'
        if (div.offsetLeft <= 0) {
          div.remove()
          clearInterval(div.timer) //清除定时
        }
      }, 200)
    }else{
        console.log("关闭");
        window.location.href="/";
    }
  }
  const dp = new DPlayer({
    container,
    live: true,
    video: {
      url: '',
      type: 'customHls',
      customType: {
        customHls: function (video, player) {
          const hls = new Hls()
          hls.loadSource(video.src)
          hls.attachMedia(video)
        }
      }
    }
  })
})
</script>
<style>
#dplayer {
  width: 100%;
  height: 400px;
  position: relative;
}
</style>
